﻿using Shared.Method;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Tools
{
    public partial class FormIperfServer : Form
    {
        //一个服务端,作用是在出现测试失败的时候重新启动服务
        private YcdStrTcpServer _ycdStrTcpServer = null;

        public FormIperfServer()
        {
            InitializeComponent();
        }

        private void FormIperfServer_Load(object sender, EventArgs e)
        {
            //打开一个监听端口，监听所有连接
            _ycdStrTcpServer = new YcdStrTcpServer(45678);
            _ycdStrTcpServer.OnAccept += _ycdStrTcpServer_OnAccept ;
            _ycdStrTcpServer.OnReceive += _ycdStrTcpServer_OnReceive;
            _ycdStrTcpServer.OnError += _ycdStrTcpServer_OnError;

            _ycdStrTcpServer.Start();

            IperfStart();
        }

        private void _ycdStrTcpServer_OnError(string obj)
        {
            AppendRichTextBox(obj);
        }

        private void _ycdStrTcpServer_OnReceive(string msg, int key)
        {
            if (msg == "RESET")
            {
                IperfStart();
            }
        }

        private void _ycdStrTcpServer_OnAccept(int obj)
        {
            AppendRichTextBox(string.Format("客户端[{0}]连接成功", obj));
        }

        /// <summary>
        /// 开启关闭IperfServer
        /// </summary>
        private void IperfStart()
        {
            //初始化
            if (ProcessClass.KillProcess("iperf3"))
            {
                AppendRichTextBox("关闭Iperf3成功");
            }
            else
            {
                AppendRichTextBox("关闭Iperf3失败");
                return;
            }

            AppendRichTextBox("正在开启iperf 服务端");

            Process p2=Process.Start("iperf3.exe", "-s");

            AppendRichTextBox("开启Iperf成功");

            return;
        }

        /// <summary>
        /// 显示日志信息
        /// </summary>
        /// <param name="value"></param>
        private void AppendRichTextBox(string value)
        {
            if (string.IsNullOrEmpty(value)) return;
            if (this.richTextBoxMsg.InvokeRequired)
            {
                Action<string> d = new Action<string>(AppendRichTextBox);
                Invoke(d, value);
            }
            else
            {
                if (this.richTextBoxMsg.Text.Length >= 5000) this.richTextBoxMsg.Text = "";
                this.richTextBoxMsg.AppendText(value);
                this.richTextBoxMsg.AppendText("\n");
            }
        }

        private void richTextBoxMsg_TextChanged(object sender, EventArgs e)
        {
            richTextBoxMsg.SelectionStart = richTextBoxMsg.Text.Length;
            richTextBoxMsg.ScrollToCaret();
        }
    }
}
